<template>
  <a-modal
    class="image-out-painting"
    v-model:open="visible"
    title="AI 扩图"
    :footer="false"
    @cancel="closeModal"
  >
    <a-row gutter="16">
      <a-col span="12">
        <h4>原始图片</h4>
        <img :src="picture.url" :alt="picture.name" style="max-width: 100%" />
      </a-col>
      <a-col span="12">
        <h4>扩图结果</h4>
        <img :src="resultImgUrl" style="max-width: 100%" loading="lazy" :alt="resultImgUrl" />
      </a-col>
    </a-row>
    <a-flex gap="16" justify="center" style="margin-top: 16px">
      <a-button type="primary" ghost @click="creatTask" :loading="!!taskId">生成图片</a-button>
      <a-button v-if="!!resultImgUrl" type="primary" @click="handleUpload" :loading="uploadLoading">应用结果</a-button>
    </a-flex>
  </a-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import {
  createPictureOutPaintingTaskUsingPost,
  getPictureOutPaintingTaskUsingGet, uploadPictureByUrlUsingPost,
  uploadPictureUsingPost
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'

interface Props {
  picture: API.PictureVO
  spaceId: number
  onSuccess: (newPicture: API.PictureVO) => void
}

const props = defineProps<Props>()


const resultImgUrl = ref<string>('')

const taskId = ref<string>()

/**
 * 创建 AI 扩图任务
 */
const creatTask = async () => {
  if (props.picture?.id == null) {
    return
  }
  // 调用后端 Ai 扩图接口
  const res = await createPictureOutPaintingTaskUsingPost({
    pictureId: props.picture.id,
    parameters: {
      xScale: 2,
      yScale: 2
    }
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('创建 AI 扩图任务成功，请耐心等待，不要退出界面')
    console.log('taskId =' + res.data.data.output?.taskId)
    // 获取taskID
    taskId.value = res.data.data.output?.taskId
    // 有 taskId 就进行轮询获取扩图结果
    startPolling()
  } else {
    message.error('图片扩展失败，' + res.data.message)
  }
}


let pollingTimer: NodeJS.Timeout = null

// 开启轮询
const startPolling = () => {
  // 校验参数
  if (taskId == null) {
    return
  }
  // 开启轮询
  pollingTimer = setInterval(async () => {
    try {
      const res = await getPictureOutPaintingTaskUsingGet({ taskId: taskId.value })
      if (res.data.code === 0 && res.data.data){
        if (res.data.data?.output?.taskStatus == 'SUCCEEDED') {
          message.success('图片扩展成功')
          resultImgUrl.value = res.data.data.output.outputImageUrl
          // 清理轮询
          clearPolling()
        } else if (res.data.data?.output?.taskStatus == 'FAILED') {
          console.log('轮询失败：' + res.data.message)
          message.error('图片扩展失败，' + res.data.message)
          // 清理轮询
          clearPolling()
        }
      }else {
        message.error('图片扩展失败，' + res.data.message)
        clearPolling()
      }
    } catch (error) {
      console.log('轮询失败：' + error)
      message.error('图片扩展失败，系统错误')
      // 清理轮询
      clearPolling()
    }
  }, 3000)
}

// 清理轮询
const clearPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
    taskId.value = null
  }
}

const uploadLoading = ref(false)

/**
 * 上传 AI 扩图后的图片
 */
const handleUpload = async () => {
  uploadLoading.value = true
  try {
    console.log("所属空间：" + props.spaceId)
    const params: API.PictureUploadRequest = { pictureUrl: resultImgUrl.value, spaceId: props.spaceId}
    if (props.picture) {
      params.id = props.picture.id
    }
    const res = await uploadPictureByUrlUsingPost(params)
    if (res.data.code === 0 && res.data.data) {
      message.success('扩展图片上传成功')
      // 将上传成功的图片信息传递给父组件
      props.onSuccess?.(res.data.data)
      closeModal()
    } else {
      message.error('扩展图片上传失败，' + res.data.message)
    }
  } catch (error) {
    message.error('扩展图片上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 是否可见
const visible = ref(false)

// 打开弹窗
const openModal = () => {
  visible.value = true
}

// 关闭弹窗
const closeModal = () => {
  visible.value = false
}

// 暴露函数给父组件
defineExpose({
  openModal
})
</script>

<style scoped>
.image-out-painting {
  text-align: center;
}

h4 {
  text-align: center;
}
</style>
